package file;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;

public class FileBrowser extends JFrame {
    private JTree tree;

    public FileBrowser() {
        setTitle("我是资源管理器");
        setVisible(true);
        setSize(300, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocation(600, 200);
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("我的电脑");
        tree = new JTree(root);
        tree.addTreeWillExpandListener(new TreeWillExpandListener() {
            @Override
                                           public void treeWillExpand(TreeExpansionEvent event)  {
                TreePath tp=event.getPath();
                DefaultMutableTreeNode node=(DefaultMutableTreeNode)tp.getLastPathComponent();
               Object o=node.getUserObject();
               File file;
                if (o instanceof  File){
                    file=(File) o;
                    File[] fs=file.listFiles();
                    if (fs!=null)
                    for (File f:fs ){
                        DefaultMutableTreeNode n=new DefaultMutableTreeNode(f);
                        if (f.isDirectory()){
                            DefaultMutableTreeNode cur=new DefaultMutableTreeNode(".");
                            DefaultMutableTreeNode pre=new DefaultMutableTreeNode("..");
                            n.add(cur);n.add(pre);
                        }
                        node.add(n);
                    }
                }
JOptionPane.showConfirmDialog(null,o);
            }
            @Override
                                           public void treeWillCollapse(TreeExpansionEvent event) {

                                           }
                                       });
                JScrollPane sp = new JScrollPane(tree);
        add(sp);

        File[] fs = File.listRoots();
        for (File file : fs) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(file);
            if (file.isDirectory()) {
                DefaultMutableTreeNode cur = new DefaultMutableTreeNode(".");
                DefaultMutableTreeNode pre = new DefaultMutableTreeNode("..");
                node.add(cur);
                node.add(pre);
            }
            root.add(node);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FileBrowser();
            }
        });
    }
}

